package com.xuan.forum.schedule;

import com.xuan.forum.cache.HotTagCahe;
import com.xuan.forum.mapper.QuestionMapper;
import com.xuan.forum.model.Question;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @创建人： xuanxuan
 * @创建时间： 2020/6/1
 * @描述： 热门标签定时任务
 */
@Component
public class HotTagTask {
    private static Logger logger = LoggerFactory.getLogger(HotTagTask.class);
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private HotTagCahe hotTagCahe;

    /**
     * 热门话题定时任务 每天凌晨一点执行
     */
    //    @Scheduled(cron = "0 0 1 * * ? *")
    @Scheduled(fixedRate = 5000)
    @PostConstruct
    public void hotTagSchedule() {
        int offset = 0;
        int limit = 5;

        List<Question> questions =  questionMapper.selectAll();
        Map<String, Integer> tagMaps = hotTagCahe.getTags();
        questions.forEach(question -> {
            //字符串 逗号替换为 |
            String replace = StringUtils.replace(question.getTag(), ",", "|").replace("，", "|");
            String[] tags =null;
            if (replace.contains("|")){
                tags = StringUtils.split(replace, "|");
            }else {
                tags = new String[]{replace};
            }
            for (String tag : tags) {
                Integer priority = tagMaps.get(tag);
                if (priority !=null){
                    tagMaps.put(tag,priority+ 5 + question.getCommentCount());
                }else {
                    tagMaps.put(tag,5+question.getCommentCount());
                }
            }
        });

        //更新标签
        hotTagCahe.updateTags(tagMaps);
    }

}
